package cxydmmszl.chapter02.t027;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;

/**
 * <li style="color: red;">Prob</li>
 * 单链表的选择排序
 * <li style="color: green;">Desc</li>
 * 给定一个无序单链表，实现单链表的选择排序(按升序排序)。
 * <li style="color: green;">Input</li>
 * 第一行一个整数 n，表示单链表的节点数量。
 * 第二行 n 个整数 val 表示单链表的各个节点。
 * <li style="color: green;">Output</li>
 * 在给出的函数内返回给定链表的头指针。
 * <li style="color: blue;">Link</li> CD139
 *
 * @author habitplus
 * @since 2021-09-10 14:04
 */
public class Main {
    private static final StreamTokenizer st =
            new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));

    private static int nextInt() {
        try {
            st.nextToken();
            return (int) st.nval;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private static class Node {
        int val;
        Node next;
        public Node(int val) {
            this.val = val;
        }
    }

    private static Node readAndGenList(int n) {
        Node tou = new Node(0), pre = tou, node;
        int num;
        for (int i = 0; i < n; i++) {
            num = nextInt();
            node = new Node(num);
            pre.next = node;
            pre = node;
        }

        return tou.next;
    }

    private static void printLinkedList(Node head) {
        StringBuilder sb = new StringBuilder();
        while (head != null) {
            sb.append(head.val).append(" ");
            head = head.next;
        }
        System.out.println(sb.toString());
    }

    private static Node selectionSort(Node h) {
        if (h == null) return h;

        int t;
        Node small, cur = h;
        while (cur != null) {
            small = getSmallestNode(cur);
            // 最小的节点就是当前节点，直接下一个
            // 最小的节点在后面，与当前节点交换值即可
            if (small != null) {
                t = cur.val;
                cur.val = small.val;
                small.val = t;
            }
            cur = cur.next;
        }

        return h;
    }

    private static Node getSmallestNode(Node h) {
        if (h == null) return null;

        Node small = h;
        while (h.next != null) {
            h = h.next;
            if (h.val < small.val) {
                small = h;
            }
        }
        return small;
    }

    private static Node getSmallestPreNode(Node h) {
        if (h == null) return null;
        Node pre = h;
        Node small = h, smallPre = null;
        h = h.next;
        while (h != null) {
            if (h.val < small.val) {
                smallPre = pre;
                small = h;
            }
            pre = h;
            h = h.next;
        }

        return smallPre;
    }

    public static void main(String[] args) {
        int n = nextInt();
        Node h = readAndGenList(n);

        h = selectionSort(h);
        printLinkedList(h);
    }
}
